package com.team9.fitness.controller;

import com.team9.fitness.entity.DietRecord;
import com.team9.fitness.service.ZRDDSSendService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * 饮食记录管理控制器
 */
@RestController
@RequestMapping("/api/diet-records")
@CrossOrigin(origins = { "*" }, allowCredentials = "false")
@Slf4j
public class DietRecordController {

    @Autowired
    private ZRDDSSendService zrddsSendService;

    /**
     * 创建饮食记录
     */
    @PostMapping
    public CompletableFuture<ResponseEntity<Map<String, Object>>> createDietRecord(@RequestBody DietRecord dietRecord) {

        log.info("创建饮食记录请求: userId={}, foodId={}, amount={}", dietRecord.getUserId(),
                dietRecord.getFoodId(), dietRecord.getAmount());

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("dietRecord", dietRecord);

        return zrddsSendService.sendBusinessRequest("DIET_RECORD_CREATE", "POST", "/api/diet-records",
                dietRecord.getUserId().toString(), requestBody)
                .thenApply(response -> {
                    Map<String, Object> result = new HashMap<>();
                    if (response.getSuccess()) {
                        result.put("success", true);
                        result.put("message", "饮食记录创建成功");
                        result.put("data", response.getData());
                        log.info("饮食记录创建成功: userId={}, foodId={}", dietRecord.getUserId(), dietRecord.getFoodId());
                    } else {
                        result.put("success", false);
                        result.put("message", response.getMessage() != null ? response.getMessage() : "饮食记录创建失败");
                        log.warn("饮食记录创建失败: userId={}, foodId={}, error={}", dietRecord.getUserId(),
                                dietRecord.getFoodId(), response.getError());
                    }
                    return ResponseEntity.ok(result);
                })
                .exceptionally(throwable -> {
                    log.error("饮食记录创建异常: userId={}, foodId={}", dietRecord.getUserId(),
                            dietRecord.getFoodId(), throwable);
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", false);
                    result.put("message", "饮食记录创建服务异常，请稍后重试");
                    return ResponseEntity.ok(result);
                });
    }

    /**
     * 获取用户指定日期的饮食记录
     */
    @GetMapping("/user/{userId}/date/{date}")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> getDietRecordsByUserAndDate(
            @PathVariable Long userId, @PathVariable String date) {

        log.info("获取用户指定日期饮食记录请求: userId={}, date={}", userId, date);

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("date", date);

        return zrddsSendService.sendBusinessRequest("DIET_RECORD_GET_BY_USER_DATE", "GET",
                "/api/diet-records/user/" + userId + "/date/" + date, userId.toString(), requestBody)
                .thenApply(response -> {
                    Map<String, Object> result = new HashMap<>();
                    if (response.getSuccess()) {
                        result.put("success", true);
                        result.put("message", "获取饮食记录成功");
                        result.put("data", response.getData());
                        log.info("获取饮食记录成功: userId={}, date={}", userId, date);
                    } else {
                        result.put("success", false);
                        result.put("message", response.getMessage() != null ? response.getMessage() : "获取饮食记录失败");
                        log.warn("获取饮食记录失败: userId={}, date={}, error={}", userId, date, response.getError());
                    }
                    return ResponseEntity.ok(result);
                })
                .exceptionally(throwable -> {
                    log.error("获取饮食记录异常: userId={}, date={}", userId, date, throwable);
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", false);
                    result.put("message", "获取饮食记录服务异常，请稍后重试");
                    return ResponseEntity.ok(result);
                });
    }

    /**
     * 获取用户指定日期的营养汇总
     */
    @GetMapping("/user/{userId}/summary/{date}")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> getNutritionSummaryByUserAndDate(
            @PathVariable Long userId, @PathVariable String date) {

        log.info("获取用户指定日期营养汇总请求: userId={}, date={}", userId, date);

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("date", date);

        return zrddsSendService.sendBusinessRequest("DIET_RECORD_GET_SUMMARY", "GET",
                "/api/diet-records/user/" + userId + "/summary/" + date, userId.toString(), requestBody)
                .thenApply(response -> {
                    Map<String, Object> result = new HashMap<>();
                    if (response.getSuccess()) {
                        result.put("success", true);
                        result.put("message", "获取营养汇总成功");
                        result.put("data", response.getData());
                        log.info("获取营养汇总成功: userId={}, date={}", userId, date);
                    } else {
                        result.put("success", false);
                        result.put("message", response.getMessage() != null ? response.getMessage() : "获取营养汇总失败");
                        log.warn("获取营养汇总失败: userId={}, date={}, error={}", userId, date, response.getError());
                    }
                    return ResponseEntity.ok(result);
                })
                .exceptionally(throwable -> {
                    log.error("获取营养汇总异常: userId={}, date={}", userId, date, throwable);
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", false);
                    result.put("message", "获取营养汇总服务异常，请稍后重试");
                    return ResponseEntity.ok(result);
                });
    }

    /**
     * 获取用户的饮食记录
     */
    @GetMapping("/user/{userId}")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> getDietRecordsByUser(@PathVariable Long userId) {

        log.info("获取用户饮食记录请求: userId={}", userId);

        return zrddsSendService.sendBusinessRequest("DIET_RECORD_GET_BY_USER", "GET",
                "/api/diet-records/user/" + userId, userId.toString(), new HashMap<>())
                .thenApply(response -> {
                    Map<String, Object> result = new HashMap<>();
                    if (response.getSuccess()) {
                        result.put("success", true);
                        result.put("message", "获取用户饮食记录成功");
                        result.put("data", response.getData());
                        log.info("获取用户饮食记录成功: userId={}", userId);
                    } else {
                        result.put("success", false);
                        result.put("message", response.getMessage() != null ? response.getMessage() : "获取用户饮食记录失败");
                        log.warn("获取用户饮食记录失败: userId={}, error={}", userId, response.getError());
                    }
                    return ResponseEntity.ok(result);
                })
                .exceptionally(throwable -> {
                    log.error("获取用户饮食记录异常: userId={}", userId, throwable);
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", false);
                    result.put("message", "获取用户饮食记录服务异常，请稍后重试");
                    return ResponseEntity.ok(result);
                });
    }

    /**
     * 删除饮食记录
     */
    @DeleteMapping("/{id}")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> deleteDietRecord(@PathVariable Long id) {

        log.info("删除饮食记录请求: id={}", id);

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("id", id);

        return zrddsSendService.sendBusinessRequest("DIET_RECORD_DELETE", "DELETE", "/api/diet-records/" + id,
                null, requestBody)
                .thenApply(response -> {
                    Map<String, Object> result = new HashMap<>();
                    if (response.getSuccess()) {
                        result.put("success", true);
                        result.put("message", "饮食记录删除成功");
                        log.info("饮食记录删除成功: id={}", id);
                    } else {
                        result.put("success", false);
                        result.put("message", response.getMessage() != null ? response.getMessage() : "饮食记录删除失败");
                        log.warn("饮食记录删除失败: id={}, error={}", id, response.getError());
                    }
                    return ResponseEntity.ok(result);
                })
                .exceptionally(throwable -> {
                    log.error("饮食记录删除异常: id={}", id, throwable);
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", false);
                    result.put("message", "饮食记录删除服务异常，请稍后重试");
                    return ResponseEntity.ok(result);
                });
    }
}
